package com.example.security.springmvc.interceptor;

import com.example.security.springmvc.model.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户认证拦截器
 * @author zhuyaotong
 * @date 2021/5/31
 */
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 在这个方法中校验用户请求的 url 是否在用户的权限范围内

        // 取出用户的身份信息
        Object obj = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);

        // 没有认证提示登录
        if (obj == null) {
            writeContent(response, "请登录");
        }

        UserDto userDto = (UserDto) obj;
        String p1Permission = "p1";
        String r1Resource = "/r/r1";
        String p2Permission = "p2";
        String r2Resource = "/r/r2";

        // 请求 url
        String requestURI = request.getRequestURI();

        if (userDto.getAuthorities().contains(p1Permission) && requestURI.contains(r1Resource)) {
            return true;
        }

        if (userDto.getAuthorities().contains(p2Permission) && requestURI.contains(r2Resource)) {
            return true;
        }

        writeContent(response, "没有权限，拒绝访问");

        return false;
    }

    /**
     * 响应信息给客户端
     * @param response
     * @param msg
     */
    private void writeContent(HttpServletResponse response, String msg) throws IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        writer.println(msg);

        writer.close();
    }

}
